package cn.wegoteam.shop.action;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import cn.wegoteam.shop.action.BaseAction;
import cn.wegoteam.shop.cache.Cache;
import cn.wegoteam.shop.cache.StaticDataCache;
import cn.wegoteam.shop.inter.CartServiceInter;
import cn.wegoteam.shop.inter.HotwordServiceInter;
import cn.wegoteam.shop.inter.ProductServiceInter;
import cn.wegoteam.shop.po.Cart;
import cn.wegoteam.shop.po.Hotword;
import cn.wegoteam.shop.po.Product;
import cn.wegoteam.shop.po.Staticdata;
import cn.wegoteam.shop.polist.JSONUtil;
import cn.wegoteam.shop.util.Const;
import cn.wegoteam.shop.util.GetReqRes;
import cn.wegoteam.shop.util.MyString;
import cn.wegoteam.shop.util.PostAndGetRequset;

@ParentPackage("default")
@Namespace("/")
@Controller
public class ProductAction extends BaseAction<Product> {
	/**
	 * 不需要拦截器的Action包：default 需添加用户拦截器的Action包：user
	 * 需要添加拦截器的Action需在Action前添加inter，如 UserInterAction
	 */
	private static final long serialVersionUID = -7214652284224332303L;
	private Staticdata p_first = new Staticdata();
	private Staticdata p_second = new Staticdata();
	private String p_brand;
	private String p_attrs = "";
	private String p_keyWord;
	private String p_order = "flag";
	private int p_desc =0;//每点击一次排序加1，根据奇偶设置升序、降序
	@Autowired
	private ProductServiceInter productService;
	@Autowired
	private HotwordServiceInter hotwordService;
	@Autowired
	private CartServiceInter cartService;
	@Action(value = "search", results = {@Result(name = SUCCESS,location =PRODUCT+"search.jsp")})
	public String search() throws Exception{
		/***************lucene 搜索*********************/
		if(!MyString.isEmpty(p_keyWord)){
			map.put("name", p_keyWord);
			List<Hotword> hs=hotwordService.getList(null, map);
			if(pageBean.getCurrentPage()<=1){
				if(hs.size()>0){
					hotwordService.executeByHql("update Hotword set searchTimes=searchTimes+1 where id="+hs.get(0).getId(),null);
				}else{
					hotwordService.save(new Hotword(p_keyWord,1,1));
				}
			}
			
			Map<String,String> params=new HashMap<String,String>();
			params.put("method","search");
			params.put("p_keyWord",p_keyWord);
			params.put("firstResults", pageBean.countOffSet()+"");
			params.put("maxResults", pageBean.getSize()+"");
			params.put("sortField", p_order);
			params.put("sortType", (p_desc%2==0?" desc":" asc"));
			params.put("SERVICE_PWD",Cache.getSetting(Const.SERVICE_PWD).getValue());
			String results=PostAndGetRequset.post(Cache.getSetting(Const.SERVICE_URL).getValue()+"lucene", params);
			
				StringBuilder sb = new StringBuilder();
				pageBean.setAllRow(JSONUtil.paserJsonHouse(results, models,sb));
				String ids="";
				if(sb.length()>0){
					ids=sb.substring(0, sb.length()-1);
				}
				if(models.size()>0){
					map.clear();
					map.put("id|in", ids);
					request.setAttribute("icon",(p_desc%2==0||p_order.equals("flag")?"&#xe623;":"&#xe626;"));//设置显示按钮,flag 表示相关度排序，值允许降序
					models = productService.getList(null, map, p_order+(p_desc%2==0?" desc":" asc"));
				}
		}
		/***************End:lucene 搜索*********************/
		if(models.size()==0){
			//lucene没有查到结果，需要从数据库模糊搜索
		}
		paramMap.put("p_keyWord",p_keyWord);
		paramMap.put("p_order", p_order);
		paramMap.put("p_desc", p_desc+"");
		return SUCCESS;
	}
	
	@Action(value = "categorys", results = { @Result(name = "success", location = WEB
			+ "categorys.jsp") })
	public String categorys() {
		return SUCCESS;
	}

	
	@Action(value = "category", results = { @Result(name = "success", location = WEB
			+ "category.jsp") })
	public String category() {
		map.put("flag|>", 0);
		map.put("brand", p_brand);
		map.put("remainder|>", 0);
		paramMap.put("p_attrs", p_attrs);
		paramMap.put("p_brand", p_brand);
		paramMap.put("p_order", p_order);
		paramMap.put("p_desc", p_desc+"");
		if (p_attrs.indexOf("|") >= 0) {
			String newAttr = p_attrs.split("\\|")[1];
			p_attrs = p_attrs.split("\\|")[0];
			if (p_attrs.contains(newAttr))
				p_attrs = p_attrs.replace(newAttr + ",", "");
			else {
				String[] samePcodes = StaticDataCache
						.getStaticdataCodes(
								StaticDataCache.getPStaticdata(newAttr)
										.getCode(), Const.STATIC_ATTR)
						.replaceAll("'", "").split(",");
				for (String samePcode : samePcodes)
					p_attrs = p_attrs.replace(samePcode + ",", "");
				p_attrs += newAttr + ",";
			}
		}
		paramMap.put("p_attrs", p_attrs);
		map.put("attr|like", p_attrs);

		List<Staticdata> staticdatas = StaticDataCache.getStaticdatas(
				Const.STATIC_ATTR, "NO");
		if (!MyString.isEmpty(p_second.getCode())) {
			map.put("type", p_second.getCode());
			p_first = StaticDataCache.getPStaticdata(p_second.getCode());
			p_second = StaticDataCache.getStaticdata(p_second.getCode());
			paramMap.put("p_second.code", p_second.getCode());
			String[] codes = MyString.isEmpty(p_second.getValue()) ? null
					: p_second.getValue().split(",");
			staticdatas = StaticDataCache.getStaticdatas(codes);
		} else if (!MyString.isEmpty(p_first.getCode())) {
			map.put("type|in", StaticDataCache.getStaticdataCodes(
					p_first.getCode(), Const.STATIC_SUBNAV));
			p_first = StaticDataCache.getStaticdata(p_first.getCode());
			paramMap.put("p_first.code", p_first.getCode());
		} else {
			p_first.setName("全部商品");
		}
		request.setAttribute("staticdatas", staticdatas);
		request.setAttribute("icon",(p_desc%2==0?"&#xe623;":"&#xe626;"));//设置显示按钮
		models = productService.getList(pageBean, map, p_order+(p_desc%2==0?" desc":" asc"));
		return SUCCESS;
	}

	@Action(value = "detail", results = { @Result(name = "success", location = WEB
			+ "detail.jsp") })
	public String detail() {
		model = productService.get(model);
		System.out.println("model----attr===="+model.getAttr());
		System.out.println("model--"+model.getAttrMaps().size());
		map.put("id", model.getId());
		productService.executeByHql("update Product set click=click+1 where id=:id", map);
		request.setAttribute(
				"content",
				model.getContent().replaceAll(
						"/ZQShop/attached/images/",
						Cache.getSetting(Const.ALIYUNOSSURL).getValue()
								+ "/attached/images/"));
		return SUCCESS;
	}
	@Action(value = "recomAndHot", results = { @Result(name = "success", location = SUBPAGES
			+ "recomAndHot.jsp") })
	public String recomAndHot() {
		map.put("type", getParameter("p_type", ""));
		map.put("flag|>", 0);
		map.put("remainder|>", 0);
		map.put("id|!=", getParameter("p_id", -1));
		pageBean.setSize(10);
		pageBean.setTotalPage(100);//不需要查询总条数，因此设置为100，=0时才查询总条数
		models = productService.getList(pageBean, map, getParameter("p_order", "sellNum")+" desc");
		return SUCCESS;
	}
	

	/**
	 * 购物车
	 * @return
	 */
	@Action(value = "myCart", results = { @Result(name = "success", location = ORDER
			+ "cartPage.jsp") })
	public String myCart() {
		pageTitle="我的购物车";
		pageMessage="<i class='iconfont mt-5'>&#xe62a;</i>&nbsp;倍力康商城购物车";
			map.put("id|in", Cart.getProductIds());
			models = productService.getList(null, map);
			request.setAttribute("carts", Cart.getCarts(models));
		return SUCCESS;
	}

	// 添加到购物车
	@Action(value = "addToCart")
	public void addToCart() {
			Integer p_id = getIntParameter("p_id");
			if(p_id == 0){
				writeStringToResponse("添加失败，不存在该商品");
				return;
			}
			model = productService.get(p_id);
			StringBuilder attrsBuilder = new StringBuilder();
			for(String attr:model.getPattrs().split(",")){
				if(attr.equals(""))
					continue;
				String attrValue = getParameter(attr, "");
				if(attrValue.equals("")){
					writeStringToResponse("添加失败，请选择商品属性");
					return;
				}else{
					attrsBuilder.append("|"+attrValue);
				}
			}
			String attrs ="";
			if(attrsBuilder.length()>0)
				attrs= attrsBuilder.toString().replaceFirst("\\|", "");
			
			Integer p_num = getParameter("p_num", 1);
			
			Map<String,Cart> cs= Cart.getCarts(false);
			if(cs.containsKey(model.getId()+"")){
				Cart c = cs.get(model.getId()+"");
				c.setNum(c.getNum()+p_num);
				c.setAttrsString(attrs);
				GetReqRes.addCookie(Const.SESS_GOODS, Cart.getCookieString(cs));
				if(getParameter("p_buyNow", "NO").equals("YES"))
					writeStringToResponse("[BUYNOW]"+model.getId());
				else
					writeStringToResponse("[OK]0");
				return;
			}
			Cart newCart = new Cart();
			newCart.setAttrsString(attrs);
			newCart.setNum(p_num);
			newCart.setProduct(model);
			cs.put(model.getId()+"",newCart);
			
			GetReqRes.addCookie(Const.SESS_GOODS, Cart.getCookieString(cs));
			session.put(Const.SESS_GOODS_NUM, cs.size());
			
			if(getParameter("p_buyNow", "NO").equals("YES"))
				writeStringToResponse("[BUYNOW]"+model.getId());
			else
				writeStringToResponse("[OK]1");
			return;

	}
	//
	@Action(value = "deleteAllFromCart")
	public void deleteAllFromCart() {
		GetReqRes.addCookie(Const.SESS_GOODS, "");
		session.put(Const.SESS_GOODS_NUM, "0");
		writeStringToResponse("[OK]");
	}
	// 删除购物车
	@Action(value = "deleteFromCart")
	public void deleteFromCart() {
			Integer p_id = getIntParameter("p_id");
			cartService.deleteFromCart(p_id+"",session);
			writeStringToResponse("[OK]"+p_id);
	}

	public Staticdata getP_first() {
		return p_first;
	}

	public void setP_first(Staticdata p_first) {
		this.p_first = p_first;
	}

	public Staticdata getP_second() {
		return p_second;
	}

	public void setP_second(Staticdata p_second) {
		this.p_second = p_second;
	}

	public String getP_brand() {
		return p_brand;
	}

	public void setP_brand(String p_brand) {
		this.p_brand = p_brand;
	}

	public String getP_attrs() {
		return p_attrs;
	}

	public void setP_attrs(String p_attrs) {
		this.p_attrs = p_attrs;
	}

	public String getP_order() {
		return p_order;
	}

	public void setP_order(String p_order) {
		this.p_order = p_order;
	}

	public int getP_desc() {
		return p_desc;
	}

	public void setP_desc(int p_desc) {
		this.p_desc = p_desc;
	}
	public String getP_keyWord() {
		return p_keyWord;
	}
	public void setP_keyWord(String p_keyWord) {
		this.p_keyWord = p_keyWord;
	}

}
